package org.javaboy.webflux_mongo.controller;

import org.javaboy.webflux_mongo.dao.UserDao;
import org.javaboy.webflux_mongo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServerResponse;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserDao userDao;


    @GetMapping
    public Flux<User> getAll() {
        return userDao.findAll();
    }

    @PostMapping
    public Mono<User> addUser(@RequestBody User user) {
        return userDao.save(user);
    }

    @PutMapping
    public Mono<ResponseEntity<User>> updateUser(@RequestBody User user) {
        return userDao.findById(user.getId())
                //展开查询结果，然后保存，实际上就是更新
                .flatMap(u -> userDao.save(user))
                //将查询结果包装成响应实体并返回，map 的参数是 flatMap 中 Lambda 的返回值，也就是更新成功的对象
                .map(u -> ResponseEntity.ok().body(u))
                .defaultIfEmpty(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public Mono<ResponseEntity<Void>> deleteById(@PathVariable String id) {
        return userDao.findById(id)
                .flatMap(u -> userDao.delete(u))
                .then(Mono.just(ResponseEntity.noContent().build()))
                .defaultIfEmpty(new ResponseEntity(HttpStatus.NOT_FOUND));
    }

    @GetMapping("/byname")
    public Flux<User> getUsersByUsername(String username) {
        return userDao.findUsersByUsernameStartingWith(username);
    }
}
